function [w,SIG] = l2relax1(y, X, tau, opt)
% L2-relaxation estimation (by the "cvx" package). 
% opt = 1. no shrinkage
%       2. linear shrinkage
%       3. nonlinear shrinkage

    % 0. house clean
    N = size(X,2);
    if isempty(y)        
        E = X;              % if no input y
    else
        E = repmat(y,1,N) - X;            
    end
    E = E-repmat(mean(E,1),size(E,1),1);            % demean error VC
    % 1. setup parameter
    SIG = SIG_fun(E,opt);  
    l = ones(N,1);
    % 2. compute for a    
    cvx_begin quiet
        variables w(N) g(1);
        minimize(w'*w/2);
        subject to
            w'*l == 1;
            norm(SIG*w+g*l,inf) <= tau;
    cvx_end  
end

function SIG = SIG_fun(E,opt)
    if opt == 1         % no shrinkage
        SIG = cov(E);
    elseif opt == 2     % linear shrinkage following Ledoit and Wolf (2004) 
        SIG = cov1para(E);
    elseif opt == 3     % nonlinear shrinkage following Ledoit and Wolf (2020)         
        SIG = analytical_shrinkage(E);
    end
    if isnan(sum(sum(SIG)))
        SIG = cov(E);        
    elseif isinf(sum(sum(SIG)))
        SIG = cov(E);        
    end    
end




